from io import BytesIO

from django.contrib.auth import logout
from django.shortcuts import render, HttpResponse, redirect
from django import forms

from tools.models.models import Admin
from tools.utils.code import check_code
from tools.utils.encrypt import md5
from tools.utils.modelform import BootStrapForm


# 这一次不使用ModelForm,使用Form来实现
class LoginForm(BootStrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput(attrs={"class": "form-control"}),
        required=True,  # 必填，不能为空
    )

    password = forms.CharField(
        label="密码",
        # render_value=True 表示当提交后,如果密码输入错误,不会自动清空密码输入框的内容
        widget=forms.PasswordInput(attrs={"class": "form-control"}, render_value=True,),
        required=True,
    )

    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput(attrs={"class": "form-control"}),
        required=True,
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)


def login(request):
    """登录"""
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'testuser/login.html', {"form": form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功, 获取到的用户名和密码
        print(form.cleaned_data)
        # {'username': '123', 'password': '123'}
        # {'username': '456', 'password': '0f54af32f41a5ba8ef3a2d40cd6ccf25'}

        # 验证码的校验
        user_input_code = form.cleaned_data.pop('code')
        image_code = request.session.get('image_code', "")
        print("user_input_code={}, image_code={}".format(user_input_code, image_code))
        if image_code.upper() != user_input_code.upper():
            form.add_error("code", "验证码错误")
            return render(request, 'testuser/login.html', {"form": form})

        # 去数据库校验用户名和密码是否正确
        admin_object = Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            return render(request, 'testuser/login.html', {"form": form})

        # 去数据库校验用户名和密码是否正确
        admin_object = Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            return render(request, 'testuser/login.html', {"form": form})

        # 如果用户名密码和验证码正确：配置cookie与session
        # 网站生成随机字符创,写到用户浏览器的cookie中,再写入到服务器的session中
        # 1.先生成一个随机字符 2.写入到本地浏览器的cookie中 3.再写入到服务器(网站)的session中
        # 但django帮我们简化成了
        # request.session['info'] = admin_object.username  # 可以存入一个值
        request.session['info'] = {'id': admin_object.id, 'username': admin_object.username}
        # 如果登录成功，session会保存7天，免登录
        request.session.set_expiry(60 * 60 * 24 * 7)
        # request.session.set_expiry(60 * 5)  # 5分钟
        return redirect('/tools/admin/list/')
        # return HttpResponse('提交成功')

    return render(request, 'testuser/login.html', {"form": form})


def image_code(request):
    """ 生成图片验证码 """

    # 调用pillow函数，生成图片
    img, code_string = check_code()
    print(code_string)

    # 写入到自己的session中,以便于后续获取验证码再进行校验
    request.session['image_code'] = code_string
    # 给session设置 60s 超时
    request.session.set_expiry(60)

    # 写入内存(Python3)
    stream = BytesIO()
    img.save(stream, 'png')

    return HttpResponse(stream.getvalue())


def logout(request):
    """ 注销 """

    # logout(request)
    request.session.clear()
    print('注销了')

    return redirect('/tools/login/')
